package com.fingard.dsp.bank.directbank.icbc02;

import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.text.StringHelper;
import com.fingard.util.ZipHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;

public class ICBC02Statement extends ICBC02Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpSenderUnderHeader = getPosRecStatement(p_reqQrySttm, retAts);
        String tmpSenderUnderTotalNum = retAts.totalNum;
        if (retAts.getWrittenRdCount() == 0) {
            if ("-1".equals(tmpSenderUnderHeader[0])) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSenderUnderHeader[1]);
            } else {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("交易为空");
            }
        } else {
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpSenderUnderTotalNum)));
        }

        retAts.writeEnd();
        return retAts;
    }
    private String[] getPosRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;
        MixFtp mixFtp = null;
        try {
            String merchantId = p_reqQrySttm.actNum;
            ActSetItem actSetItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "pos");
            if (actSetItem != null && StringHelper.hasAnyChar(actSetItem.merchantId)) {
                merchantId = actSetItem.merchantId;
            }else{
                WriteBankLogLn2("未找到账号:[" + p_reqQrySttm.actNum + "]商户配置信息!----直接采用账号");
            }
            StringBuilder sbFileContent = new StringBuilder();
            String downFileName = p_reqQrySttm.busDate+"_"+merchantId + ".zip";
            
            String localFilePath = createTempFileDirectory() + File.separator + downFileName;

            String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
            if ("ftp".equalsIgnoreCase(posRecRequestType) || "sftp".equalsIgnoreCase(posRecRequestType)|| true) {
            	FtpSet ftpSet = bankFront.getFtpSet("pos");
                //ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/");
                WriteBankLogLn2("工行POS对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn2("工行POS对账单所在服务器路径:" + StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName);
                WriteBankLogLn2("工行POS对账单保存本地路径:" + localFilePath);
                if(!new File(localFilePath).exists()){
                    WriteBankLogLn2("下载目录：" + ftpSet.downDir+"，下载文件名："+downFileName);
                    mixFtp = new MixFtp(ftpSet);
                    FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(ftpSet.downDir, downFileName, localFilePath);
                    if (!ftpReceiver.isCompleted) {
                        tmpRespCode = "-1";
                        tmpRespInfo = "建设银行POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
                    }
                }
            }else {
                String bkFolder = bankFront.getStrValueByFor("bankFolder", "pos");
                String posFile = StringHelper.trimEndFileSp(bkFolder)+File.separator+downFileName;
                if(!FileHelper.existFile(posFile)){
                    tmpRespCode = "-1";
                    tmpRespInfo = "文件"+posFile+"不存在";
                }
            }
            String tempStr = localFilePath.replace(".zip","")+ File.separator+p_reqQrySttm.busDate+"_"+merchantId + File.separator +"RZ"+p_reqQrySttm.busDate+".txt";
            if(!new File(tempStr).exists()){
                ZipHelper.unzipFile(localFilePath, createTempFileDirectory());
            }
            if ("".equals(tmpRespCode)) {
                tmpRespCode = "0";
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }

                WriteBankLogLn2("工行POS对账单解压后路径:\r\n" + tempStr);
                sbFileContent.append(FileHelper.readFileText(tempStr, "GBK"));
                String tmpStrRet = sbFileContent.toString();
                WriteBankLogLn2("工行POS对账单响应数据:\r\n" + tmpStrRet);

                StringReader strReader = new StringReader(tmpStrRet);
                BufferedReader tmpReader = new BufferedReader(strReader);

                boolean isContinue = false;
                while (true) {
                    String eachline = tmpReader.readLine();
                    if (eachline == null || "".equals(eachline)) {
                        break;
                    }
                    if(eachline.startsWith("1")){
                        continue;
                    }
                    totalNum++;
                    isContinue = true;
                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                    tmpRetDetail.askNumber = new String(eachline.getBytes("GBK"),283,23).trim();
                    tmpRetDetail.bkSeq = "";
                    int tmp= Integer.parseInt(new String(eachline.getBytes("GBK"),170,18));
                    tmpRetDetail.amount = amountDivide100(tmp+"");
                    tmpRetDetail.cdFlag = "22";
                    tmp = Integer.parseInt(new String(eachline.getBytes("GBK"),229,18));
                    tmpRetDetail.fee = amountDivide100(tmp+"");
                    String tempTime = new String(eachline.getBytes("GBK"),306,8)+new String(eachline.getBytes("GBK"),331,8).replace(".","");
                    tmpRetDetail.busTime = tempTime;
                    tmpRetDetail.oppAct = new String(eachline.getBytes("GBK"),146,19).trim();
                    tmpRetDetail.transState = TransState.Success;
                    retAts.writeRetDetail(tmpRetDetail);
                }

                if (!isContinue) {
                    tmpRespCode = "0";
                    tmpRespInfo = "没有符合条件的记录!";
                }
            }

        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = LogHelper.getStackTrace(ex);
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }
}
